import React, { useEffect } from 'react';
import { StyleSheet} from 'react-native';
import { View, Colors } from 'react-native-ui-lib';
import Animated, {
  useAnimatedStyle,
  withRepeat,
  withSpring,
  withSequence,
  withTiming,
  useSharedValue,
  withDelay,
  Easing,
} from 'react-native-reanimated';

// 创建可动画化的View组件
const AnimatedView = Animated.createAnimatedComponent(View);

// 定义组件属性接口
interface AIAvatarProps {
  // AI状态：未激活、已激活、正在听、正在说话、思考中、错误
  status?:  'inactive' | 'active' | 'voiceinput' | 'listening' | 'speaking' | 'thinking' | 'error';
  // 音频音量级别（0-1）
  audioLevel?: number;
}

export const AIAvatar: React.FC<AIAvatarProps> = ({ status = 'inactive', audioLevel = 0 }) => {
  // 添加共享值来控制动画
  const scale = useSharedValue(1);
  const opacity = useSharedValue(1);

  // 监控状态变化
  useEffect(() => {
    console.log('AIAvatar status changed:', status);
    console.log('AIAvatar audioLevel:', audioLevel);

    if (status === 'active') {
      scale.value = withSpring(1.2);
      opacity.value = withTiming(2);
    } else if (status === 'voiceinput') {
      scale.value = withSpring(1.4, {
        damping: 12,
        stiffness: 100,
      });
      opacity.value = withTiming(1);
    } else {
      scale.value = withSpring(1);
      opacity.value = withTiming(1);
    }
  }, [status, audioLevel]);

  // 先定义颜色获取函数
  const getStatusColor = () => {
    const color = {
      inactive: Colors.avatarInactive,
      active: Colors.avatarActive,
      voiceinput: Colors.avatarVoiceinput,
      listening: Colors.avatarlistening,
      speaking: Colors.avatarSpeaking,
    }[status] || Colors.avatarActive;
    
    return color;
  };

  // 再定义样式
  const styles = StyleSheet.create({
    container: {
      width: 120,
      height: 120,
      justifyContent: 'center' as const,
      alignItems: 'center' as const,
      backgroundColor: 'transparent',  // 添加透明背景
      zIndex: 1000, 
    },
    core: {
      width: 50,        // 120 * 0.3
      height: 50,       // 120 * 0.3
      borderRadius: 30,
      backgroundColor: getStatusColor(),
    },
    wave: {
      position: 'absolute' as const,
      width: 50,
      height: 50,
      borderRadius: 30,
      backgroundColor: getStatusColor(),
    },
  });

  // 核心圆点的脉动动画样式
  const pulseStyle = useAnimatedStyle(() => ({
    transform: [{
      scale: withRepeat(
        withSequence(
          withTiming(1, { duration: 1000 }),    // 1秒内缩小到原始大小
          withTiming(1.1, { duration: 1000 })   // 1秒内放大10%
        ),
        -1,  // 无限循环
        true // 来回播放
      )
    }],
    opacity: opacity.value
  }));

  // 第一层波纹动画样式
  const waveStyle1 = useAnimatedStyle(() => {
    const baseScale = 1.2; // 统一的基础缩放
    const scaleFactor = status === 'speaking'
      ? baseScale + (audioLevel * 0.55)
      : baseScale;

    return {
      transform: [{
        scale: withSpring(scaleFactor, {
          damping: 6,
          stiffness: 80,
        })
      }],
      opacity: withTiming(
        status === 'speaking' ? 0.6 : 
        status === 'active' ? 0.3 : 
        status === 'inactive' ? 0.3 : 0,  // inactive 和 active 状态都显示波纹
        {
          duration: 1500,
          easing: Easing.out(Easing.ease),
        }
      )
    };
  });

  // 第二层波纹动画样式（延迟100ms）
  const waveStyle2 = useAnimatedStyle(() => {
    const baseScale = status === 'voiceinput' ? 1.6 : status === 'inactive' ? 1.2 : 1.4;
    const scaleFactor = status === 'speaking'
      ? baseScale + (audioLevel * 0.55)
      : baseScale;

    return {
      transform: [{
        scale: withDelay(
          100,  // 延迟100ms
          withRepeat(
            withSpring(scaleFactor, {
              damping: status === 'voiceinput' ? 12 : 6,  // voiceinput 态下减小阻尼
              stiffness: status === 'voiceinput' ? 100 : status === 'inactive' ? 40 : 80,  // voiceinput 状态下增加刚度
            }),
            -1,
            true
          )
        )
      }],
      opacity: withDelay(
        100,
        withTiming(
          status === 'speaking' ? 0.4 : 
          status === 'voiceinput' ? 0.5 :  // 增加 voiceinput 状态下的透明度
          status === 'active' ? 0.2 : 
          status === 'inactive' ? 0.2 : 0,
          {
            duration: 1000,
            easing: Easing.out(Easing.ease),
          }
        )
      )
    };
  });

  // 第三层波纹动画样式（延迟200ms）
  const waveStyle3 = useAnimatedStyle(() => {
    const baseScale = status === 'inactive' ? 1.3 : 1.6;
    const scaleFactor = status === 'speaking'
      ? baseScale + (audioLevel * 0.55)  // 说话时波纹大小随音量变化
      : baseScale;

    return {
      transform: [{
        scale: withDelay(
          200,  // 延迟200ms
          withRepeat(
            withSpring(scaleFactor, {
              damping: 6,
              stiffness: status === 'inactive' ? 40 : 80,
            }),
            -1,
            true
          )
        )
      }],
      opacity: withDelay(
        200,
        withRepeat(
          withTiming(status === 'speaking' ? 0.3 : 0.1, {  // 最外层波纹透明度最低
            duration: status === 'inactive' ? 3000 : 1500,
            easing: Easing.out(Easing.ease),
          }),
          -1,
          true
        )
      )
    };
  });

  // 添加容器的动画样式
  const containerAnimatedStyle = useAnimatedStyle(() => ({
    transform: [{ scale: scale.value }],
  }));

  // 渲染波纹
  const renderWaves = () => {
    if (status === 'speaking') {
      // 说话状态显示三层波纹
      return (
        <>
          <AnimatedView
            style={[styles.wave, waveStyle1, { backgroundColor: getStatusColor() }]}
          />
          <AnimatedView
            style={[styles.wave, waveStyle2, { backgroundColor: getStatusColor() }]}
          />
          <AnimatedView
            style={[styles.wave, waveStyle3, { backgroundColor: getStatusColor() }]}
          />
        </>
      );
    } else if (status === 'voiceinput') {
      // voiceinput 状态显示两层波纹
      return (
        <>
          <AnimatedView
            style={[styles.wave, waveStyle1, { backgroundColor: getStatusColor() }]}
          />
          <AnimatedView
            style={[styles.wave, waveStyle2, { backgroundColor: getStatusColor() }]}
          />
        </>
      );
    }
    // inactive 和 active 状态显示一层波纹
    return (
      <AnimatedView
        style={[styles.wave, waveStyle1, { backgroundColor: getStatusColor() }]}
      />
    );
  };

  // 渲染整个头像组件
  return (
    <Animated.View style={[styles.container, containerAnimatedStyle]}>
      {renderWaves()}
      <AnimatedView
        style={[
          styles.core,
          pulseStyle,
          { backgroundColor: getStatusColor() }
        ]}
      />
    </Animated.View>
  );
} 